﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    class DBConnector
    {
        private MySqlConnection connection;
        private String server;
        private String database;
        private String uid;
        private String password;

        public DBConnector()
        {
            initialize();
        }

        private void initialize()
        {
            server = "localhost";
            database = "payroll";
            uid = "root";
            password = "p@ssword";
            string connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
            connection = new MySqlConnection(connectionString);
        }

        public bool openConnection()
        {
            try
            {
                connection.Open();
                return true;
            }
            catch (MySqlException ex)
            {
                switch (ex.Number)
                {
                    case 0: MessageBox.Show("Cannot connect to server. Please contact the administrator.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        break;
                    case 1045: MessageBox.Show("Invalid database username/password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        break;
                }
                return false;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message + "\n" + e.StackTrace);
                return false;
            }
        }

        public bool closeConnection()
        {
            try
            {
                connection.Close();
                return true;
            }
            catch (MySqlException ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
        }

        public MySqlConnection getConnection()
        {
            return connection;
        }

    }
}
